export default class SocketService {

  // 单例
  static instance = null

  static get Instance() {
    if (!this.instance) {
      this.instance = new SocketService()
    }
    return this.instance
  }

  ws = null
  connected = false
  sendRetryCount = 0
  connRetryCount = 0

  callBackMapping = {}

  // 定义连接服务器的方法
  connect() {
    if (!window.WebSocket) {
      return console.log('您的浏览器不支持WebSocket')
    }
    this.ws = new WebSocket('ws://localhost:9998')

    this.ws.onopen = () => {
      console.log('连接服务端成功')
      this.connected = true
      this.connRetryCount = 0
    }

    this.ws.onclose = () => {
      console.log('连接服务端失败')
      this.connected = false
      this.connRetryCount++
      setInterval(() => {
        this.connect()
      }, 3000 * this.connRetryCount)
    }

    this.ws.onmessage = msg => {
      console.log('服务端获取到数据')
      const recv = JSON.parse(msg.data)
      const socketType = recv.socketType
      if (this.callBackMapping[socketType]) {
        const action = recv.action
        if (action === 'getData') {
          const realData = JSON.parse(recv.data)
          this.callBackMapping[socketType].call(this, realData)
        } else if (action === 'fullScreen') {
          this.callBackMapping[socketType].call(this, recv)
        } else if (action === 'themeChange') {
          this.callBackMapping[socketType].call(this, recv)
        }
      }
    }
  }

  registerCallback(socketType, callback) {
    this.callBackMapping[socketType] = callback
  }

  unRegisterCallback(socketType) {
    // delete this.callBackMapping[socketType]
    this.callBackMapping[socketType] = null
  }

  send(data) {
    if (this.connected) {
      this.sendRetryCount = 0
      this.ws.send(JSON.stringify(data))
    } else {
      this.sendRetryCount++
      setInterval(() => {
        this.ws.send(JSON.stringify(data))
      }, this.sendRetryCount * 500)
    }
  }
}